Conditionals有條件的 << 
Previous Next >> List Less Than Ten列出少於十
Checking for equality and comparators in general檢查是否相等以及一般的比較器
A fundamental thing you want to do with your program is check whether some number is equal to another. Say the user tells you how many questions they answered incorrectly on a practice exam, and depending on the number of correctly-answered questions, you can suggest a specific course of action. For integers, strings, floats, and many other variable types, this is done with a simple syntax: ==. To explicitly check inequality, use !=.
if a == 3:
print("the variable has the value 3")
elif a != 3:
print("the variable does not have the value 3")
Notice how in this example, the condition is redundant. In the first condition we are checking whether the variable a has the value 3 and in the second, we are checking whether a does NOT have the value 3. However, if the first condition is not true (a is in fact not 3), then the second condition is by definition true. So a more efficient way to write the above conditional is like this:
if a == 3:
print("the variable has the value 3")
else:
print("the variable does not have the value 3")
The same equality / inequality comparisons work for strings.
您要對程序執行的基本操作是檢查某個數字是否等於另一個數字。假設用戶告訴您在練習考試中有多少個錯誤回答的問題,並且根據正確回答的問題數,您可以提出具體的操作建議。對於整數,字符串,浮點數和許多其他變量類型,這是通過簡單的語法完成的:==。要顯式檢查不平等,請使用!=。
  
if a == 3: 
  print("the variable has the value 3")
elif a != 3:
  print("the variable does not have the value 3")
請注意,在此示例中,條件是多餘的。在第一個條件中,我們正在檢查變量是否a具有值3,在第二個條件中,我們正在檢查變量是否a不具有值3。但是,如果第一個條件不成立(a實際上不是3),則第二個條件根據定義,條件是正確的。因此,編寫上述條件的更有效方法如下:
if a == 3: 
  print("the variable has the value 3")
else:
  print("the variable does not have the value 3")
相同的相等/不相等比較適用於字符串。
Conditionals有條件的 << 
Previous Next >> List Less Than Ten列出少於十
 
        
    
      
        
            
            
            Copyright © All rights reserved | This template is made with  by Colorlib